<!-- 党员活动台账 -->
<template>
  <el-dialog
    :title="title"
    :visible.sync="isShowAdd"
    width="40%"
    :show-close="false"
    destroy-on-close
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-form
      :model="dialogForm"
      ref="formRef"
      label-width="80px"
      :rules="formRules"
    >
      <el-form-item label="活动类型" prop="activityType">
        <el-select
          v-model="dialogForm.activityType"
          clearable
          filterable
          style="width: 100%"
          placeholder="请选择活动类型"
        >
          <el-option
            v-for="item in typeArr"
            :key="item.key"
            :label="item.value"
            :value="item.key"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="活动主题" prop="activityTheme">
        <el-input
          v-model="dialogForm.activityTheme"
          placeholder="请填写活动主题"
        ></el-input>
      </el-form-item>

      <el-form-item label="开始时间" prop="activityStartTime">
        <el-date-picker
          style="width: 100%"
          v-model="dialogForm.activityStartTime"
          type="datetime"
          placeholder="请选择开始时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="activityEndTime">
        <el-date-picker
          style="width: 100%"
          v-model="dialogForm.activityEndTime"
          type="datetime"
          placeholder="请选择结束时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="活动地点" prop="activityPlace">
        <!-- {{ dialogForm.activityPlace }}{{ placeArr }} -->
        <el-select
          v-model="dialogForm.activityPlace"
          clearable
          filterable
          style="width: 100%"
          placeholder="请选择活动地点"
        >
          <el-option
            v-for="item in placeArr"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="参与人员" prop="participant">
        <el-select
          v-model="dialogForm.participant"
          clearable
          filterable
          multiple
          style="width: 100%"
          placeholder="请选择参与人员"
        >
          <el-option
            v-for="item in participantArr"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="活动内容" prop="activityContent">
        <el-input
          type="textarea"
          autosize
          v-model="dialogForm.activityContent"
          placeholder="请输入活动内容"
        ></el-input>
      </el-form-item>

      <el-form-item label="活动照片" prop="">
        <el-upload
          :action="uploadUrl2"
          list-type="picture-card"
          accept=".jpg,.jpeg,.png,.gif"
          :on-preview="handlePictureCardPreview"
          :on-remove="removePic"
          :on-success="onSuccessPic"
          :headers="headers"
          :file-list="coverUrlPic"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible" :modal="false">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>

      <el-form-item label="附件" prop="accessoryUrl">
        <el-upload
          :action="uploadUrl2"
          :headers="headers"
          :on-success="onSuccessFile"
          accept=".bmp, .gif, .jpg, .jpeg, .png, .doc, .docx, .xls, .xlsx, .ppt, .pptx, .html, .htm, .txt, .rar, .zip, .gz, .bz2, .mp4, .avi, .rmvb, .asf, .wmv, .mov, .pdf"
          :on-remove="removeFile"
          :file-list="accessoryUrlFile"
        >
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="reset">取 消</el-button>
      <el-button v-if="!dialogForm.userId" @click="submitData('formRef', 1)"
        >保存草稿</el-button
      >
      <el-button type="primary" @click="submitData('formRef', 2)"
        >提 交</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
import { uploadUrl2 } from "@/const";
import { getToken } from "@/utils/auth";

import {
  apiTbUserInfoList, // 参与人员
  apiAllEnumMap, // 活动类型
} from "@/api2/ledger";

import { getActivityListApi, PlaceListApi } from "@/api2/politicalActivity";

export default {
  components: {},
  props: {
    title: {
      type: String,
    },
    isShowAdd: {
      type: Boolean,
      default: false,
    },
    rowFormObj: {
      type: Object,
      default: () => {},
    },
  },
  watch: {
    rowFormObj: {
      handler(newVal) {
        if (newVal && newVal.userId) {
          console.log("newValnewVal", newVal.dqActivityId);

          let data = {
            activityContent: newVal.activityContent,
            participant: JSON.parse(newVal.participant).map((v) => v.id),
            activityPlace: Number(newVal.activityPlace),
            activityType: Number(newVal.activityType),
            activityTheme: newVal.activityTheme,
            activityStartTime: new Date(newVal.activityStartTime),
            activityEndTime: new Date(newVal.activityEndTime),
            userId: newVal.userId,
            dqActivityId: newVal.dqActivityId,
          };
          this.dialogForm = data;
          // 活动照片
          this.coverUrlPic = JSON.parse(newVal.coverUrl).map((v) => {
            return {
              name: v,
              url: v,
              uid: v,
            };
          });
          data.coverUrl = JSON.parse(newVal.coverUrl).map((v) => {
            return v;
          });

          // 附件
          this.accessoryUrlFile = JSON.parse(newVal.accessoryUrl).map((v) => {
            return {
              name: v.accessoryName,
              url: v.accessoryUrl,
              uid: v.accessoryUrl,
            };
          });
          data.accessoryUrl = JSON.parse(newVal.accessoryUrl).map((v) => {
            return {
              accessoryName: v.accessoryName,
              accessoryUrl: v.accessoryUrl,
            };
          });
        }
      },
      deep: true,
      immediate: true,
    },
  },
  data() {
    return {
      uploadUrl2,
      headers: {
        Authorization: getToken(),
        platform: "WEB",
      },
      // -----------------
      coverUrlPic: [], // 保存上传的图片
      accessoryUrlFile: [], // 保存上传的附件
      dialogImageUrl: "",
      dialogVisible: false,
      participantArr: [], // 参与人员
      placeArr: [],
      urls: [],
      srcList: [],
      whetherVideosArr: [], // 多个视频链接
      formRules: {
        activityTheme: [
          {
            required: true,
            message: "请填写活动主题",
            trigger: "blur",
          },
        ],

        activityType: [
          {
            required: true,
            message: "请选择活动类型",
            trigger: "change",
          },
        ],
        activityStartTime: [
          {
            type: "date",
            required: true,
            message: "请选择开始时间",
            trigger: "change",
          },
        ],
        activityEndTime: [
          {
            type: "date",
            required: true,
            message: "请选择结束时间",
            trigger: "change",
          },
        ],
        activityPlace: [
          {
            required: true,
            message: "请选择活动地点",
            trigger: "change",
          },
        ],
        participant: [
          {
            required: true,
            message: "请选择参与人员",
            trigger: "change",
          },
        ],

        activityContent: [
          {
            required: true,
            message: "请输入活动内容",
            trigger: "blur",
          },
        ],
        accessoryUrl: [
          {
            required: true,
            message: "请选择文件",
            trigger: "change",
          },
        ],

        learningType: [
          { required: true, message: "请选择学习类型", trigger: "change" },
        ],

        url: [
          {
            required: true,
            message: "请输入链接地址",
            trigger: "blur",
          },
        ],
      },
      dialogForm: {
        seriesCoverUrl: [],
        fileUrl: [],
        coverUrl: [],
        accessoryUrl: [],
        participant: [],
        activityPlace: "",
      },
      total: 0,
      listLoading: false,
      listArr: [],
      // ---------------------
      Status: [
        {
          key: null,
          value: "全部",
        },
        {
          value: "未开始",
          key: 1,
        },
        {
          value: "进行中",
          key: 2,
        },
        {
          value: "已结束",
          key: 3,
        },
      ],
      typeArr: [], // 活动类型
      isNoCommon: true, // 是普通人员
      listParams: {
        pageNum: 1,
        pageSize: 10,
        djDeptId: JSON.parse(sessionStorage.getItem("loginUserinfo")).djDeptId,
        activityStatus: null,
        activityType: null,
      },
    };
  },
  created() {
    this.init();
  },
  methods: {
    // 获取人员身份信息
    getUserInfo() {
      let userInfo = sessionStorage.getItem("loginUserinfo");
      if (userInfo) {
        const INFO = JSON.parse(userInfo);
        if (INFO.permission && INFO.permission.indexOf("common") > -1) {
          this.isNoCommon = true;
        } else {
          this.isNoCommon = false;
        }
      }
    },
    // 将标准按时间转为时间戳
    getTimeStamp(chinaStandardTime) {
      return new Date(chinaStandardTime).getTime();
    },

    // 获取活动类型
    getAllEnumMap() {
      apiAllEnumMap()
        .then((res) => {
          if (res.code == 0) {
            this.typeArr = res.data;
          } else {
            this.typeArr = [];
          }
        })
        .catch((err) => {
          this.typeArr = [];
        });
    },

    // 图片上传--成功
    onSuccessPic(response, file) {
      this.coverUrlPic.push({
        name: file.response.data.fileName,
        url: file.response.data.url,
        uid: file.uid,
      });
      this.dialogForm.coverUrl.push(file.response.data.url);
    },
    removePic(file) {
      let i = this.coverUrlPic.findIndex((v) => {
        return file.uid == v.uid;
      });
      this.coverUrlPic.splice(i, 1);
      this.dialogForm.coverUrl.splice(i, 1);
    },

    // 文件上传
    onSuccessFile(response, file) {
      console.log(file);
      this.accessoryUrlFile.push({
        name: file.response.data.fileName,
        url: file.response.data.url,
        uid: file.uid,
      });
      this.dialogForm.accessoryUrl.push({
        accessoryUrl: file.response.data.url,
        accessoryName: file.response.data.fileName,
      });
      this.$refs.formRef.clearValidate("accessoryUrl");
    },

    removeFile(file) {
      let i = this.accessoryUrlFile.findIndex((v) => {
        return file.uid == v.uid;
      });
      this.accessoryUrlFile.splice(i, 1);
      this.dialogForm.accessoryUrl.splice(i, 1);
    },

    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },

    // 获取参与人员列表
    getTbUserInfoList() {
      apiTbUserInfoList({ djDeptId: this.listParams.djDeptId })
        .then((res) => {
          if (res.code == 0) {
            this.participantArr = res.data;
          } else {
            this.participantArr = [];
          }
        })
        .catch((err) => {
          console.log(err);
          this.participantArr = [];
        });
    },

    getPlaceList() {
      PlaceListApi()
        .then((res) => {
          if (res.code === 0) {
            this.placeArr = res.data;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },

    // 添加链接
    addUrl() {
      let index = this.whetherVideosArr.length;
      this.whetherVideosArr.push({
        index,
        url: "",
      });
    },

    // 删除链接
    delUrl(index) {
      this.whetherVideosArr.splice(index, 1);
    },


    // 删除上传的文件
    onRemoveFile(file) {
      for (let i = 0; i < this.dialogForm.fileUrl.length; i++) {
        if (file.uid == this.dialogForm.fileUrl[i].uid) {
          this.dialogForm.fileUrl[i].splice(i, 1);
        }
      }
    },

    // 限制文件上传大小
    beforeAvatarUpload(file) {
      let size = 200;
      const isLtM = file.size / 1024 / 1024 < size;

      if (!isLtM) {
        this.$message.error(`上传文件大小不能超过${size} MB!`);
      }
      return isLtM;
    },

    // 封面上传成功
    handleSuccess(res) {
      this.dialogForm.seriesCoverUrl = [];
      if (res.code === 0) {
        this.dialogForm.seriesCoverUrl.push({
          name: res.data.fileName,
          url: res.data.url,
        });

        this.$nextTick(() => {
          this.$refs.formRef.validateField("seriesCoverUrl"); // 手动触发fileList校验规则
        });
        this.$forceUpdate();
      } else {
        this.msgError("上传失败");
        this.dialogForm.seriesCoverUrl = [];
      }
    },

    // 文件上传成功
    handleSuccessFile(res) {
      if (res.code === 0) {
        this.dialogForm.fileUrl.push({
          name: res.data.fileName,
          url: res.data.url,
        });
        this.$refs.formRef.validateField("fileUrl"); // 手动触发fileList校验规则
      } else {
        this.msgError("上传失败");
        this.dialogForm.fileUrl = [];
      }
    },

    // 提交
    submitData(name, type) {
      console.log(this.dialogForm);
      this.$refs[name].validate((valid) => {
        if (valid) {
          let data = {
            activityType: this.dialogForm.activityType, //活动类型
            activityTheme: this.dialogForm.activityTheme, // 活动主题
            activityPlace: this.dialogForm.activityPlace, // 活动地点
            activityContent: this.dialogForm.activityContent, // 活动内容
            coverUrl: JSON.stringify(this.dialogForm.coverUrl), // 照片
            accessoryUrl: JSON.stringify(this.dialogForm.accessoryUrl), // 附件
            djDeptId: JSON.parse(sessionStorage.getItem("loginUserinfo"))
              .djDeptId,
            participant: [], // 参与人员
            activityStartTime: this.getTimeStamp(
              this.dialogForm.activityStartTime
            ),
            activityEndTime: this.getTimeStamp(this.dialogForm.activityEndTime),
            dqActivityId: this.dialogForm.dqActivityId,
          };

          console.log(data.activityStartTime, data.activityEndTime);
          if (data.activityStartTime > data.activityEndTime) {
            this.msgInfo("开始时间应该小于结束时间");
            return;
          }

          // 参与人员
          for (let i = 0; i < this.participantArr.length; i++) {
            for (let j = 0; j < this.dialogForm.participant.length; j++) {
              if (this.dialogForm.participant[j] == this.participantArr[i].id) {
                data.participant.push({
                  id: this.participantArr[i].id,
                  name: this.participantArr[i].name,
                });
              }
            }
          }
          data.participant = JSON.stringify(data.participant);
          data.userId = JSON.parse(sessionStorage.getItem("loginUserinfo")).uid;
          if (type == 1) {
            // 保存草稿
            this.$emit("saveDraft", data);
          } else {
            this.$emit("addActivity", data);
          }
          this.reset();
        }
      });
    },

    reset() {
      this.dialogForm = {
        seriesCoverUrl: [],
        fileUrl: [],
        coverUrl: [],
        accessoryUrl: [],
        participant: [],
        activityPlace: "",
      };
      this.coverUrlPic = [];
      this.accessoryUrlFile = [];
      this.$nextTick(() => {
        this.$refs["formRef"].clearValidate();
      });
      this.$emit("resetAdd");
    },

    // 项目初始化
    init() {
      this.getUserInfo();
      // this.getList();
      this.getAllEnumMap();
      this.getTbUserInfoList();
      this.getPlaceList();
    },
  },
};
</script>
